#include "Glow.h"
#include <sstream>
#include <iostream>

using namespace std;
using namespace glow;

int main(int argc, char **argv)
{
	// INITIALISATION
	GlowDevice *device = GlowDevice::getInstance();
	device->init(800, 600);
	
	Renderer *rdr = device->getRenderer();
	EventManager *emgr = device->getEventManager();
	
	SkyBox sb;
	sb.load("../media/skybox/interZP.png",
		"../media/skybox/interZN.png",
		"../media/skybox/interYP.png",
		"../media/skybox/interYN.png",
		"../media/skybox/interXP.png",
		"../media/skybox/interXN.png");
	
	Camera c(Vector3d(15, 15, 5));
	c.setSensivity(1.0);
	c.setSpeed(5.0);
	
	// CHARGEMENT
	Mesh *tric = MeshFactory::create("../media/triceratops.off");
	tric->genNormals();
	tric->setAmbient(Color4f(0.0, 0.0, 0.0));
	tric->setSpecular(Color4f(0.1, 0.1, 0.1));
	tric->setDiffuse(Color4f(1.0, 1.0, 1.0));
	tric->setShininess(1.0);

	Mesh *ext = MeshFactory::create("../media/extincteur.obj");
	ext->genNormals(true);
	ext->setTexture("../media/ext_map.png");
	ext->setAmbient(Color4f(0.4, 0.4, 0.4));
	ext->setSpecular(Color4f(10.0, 10.0, 10.0));
	ext->setDiffuse(Color4f(0.0, 0.0, 0.0));
	ext->setShininess(0.5);

	Light l1(GL_LIGHT0);
	l1.setPosition(Vector3f(0, 50, 0));
	l1.setDiffuse(Color4f(1.0, 1.0, 1.0));

	bool quit = false;
	bool show = false;
	bool drawNormals = false;
	device->showCursor(show);
	
	// MAIN LOOP
	while(!emgr->quit() && !quit)
	{
		emgr->getEvent();
		c.getEvent();
		c.animate();
		sb.setPosition(c.getPosition());
		
		rdr->beginScene();
		c.look();
		sb.draw();
		
		l1.draw();

		l1.on();
		tric->draw();
		l1.off();

		rdr->pushMatrix();
		rdr->translate(Vector3d(20, 5, 0));
		rdr->rotate(-90,Vector3d(1.,0.,0.));
		l1.on();
		ext->draw();
		l1.off();
		rdr->popMatrix();

		if(drawNormals)
		  {
		    rdr->pushMatrix();
			rdr->translate(Vector3d(20, 5, 0));
			rdr->rotate(-90,Vector3d(1.,0.,0.));
			ext->drawNormals();
			rdr->popMatrix();
		    tric->drawNormals();
		  }

		std::ostringstream oss;
		oss<<device->getFPS();
		std::string resultFPS = oss.str();
		
		device->setWindowTitle("DemoMesh Window | FPS : "+resultFPS);
		rdr->endScene();

		if(emgr->isKeyDownOnce(GLFW_KEY_ESC)) quit = true;
		if(emgr->isKeyDownOnce('B'))
		{
			show = !show;
			device->showCursor(show);
		}
		if(emgr->isKeyDownOnce('N')) drawNormals = !drawNormals;
		if(emgr->isKeyDownOnce('K')) rdr->setPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
		if(emgr->isKeyDownOnce('L')) rdr->setPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		if(emgr->isKeyDownOnce('M')) rdr->setPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	}

	delete tric;
	delete ext;
	GlowDevice::destroy();
	
	return 0;
}
